package tech.dongliang.system.controller;

import cn.hutool.crypto.digest.DigestUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tech.dongliang.common.enums.EBizError;
import tech.dongliang.common.exception.BizException;
import tech.dongliang.common.response.CommonResponse;
import tech.dongliang.shiro.ShiroUtils;


@Controller
public class LoginController {

    @GetMapping(value = "/login")
    public String login() throws Exception {
        return "login";
    }

    @ResponseBody
    @PostMapping(value = "/login")
    public CommonResponse login(String username, String password) throws Exception {
        password = DigestUtil.md5Hex(password);
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            throw new BizException(EBizError.LOGIN_ERROR);
        }
        return CommonResponse.success("登陆成功");
    }

    @GetMapping(value = "/logout")
    public String logout() throws Exception {
        ShiroUtils.logout();
        return "redirect:/login";
    }
}
